<template>
  <!-- 企业套餐 -->
  <div class="app-container">
    <div class="form-container">
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="queryParams.name" size="small" placeholder="请输入套餐名称" clearable />
        </el-form-item>
        <el-form-item label="套餐类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择套餐类型" clearable size="small">
            <el-option v-for="(item,index) in companyTypeOptions" :key="index" :label="item.name" :value="item.id">{{ item.name }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="套餐状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="btns-group">
      <systemBtns :single="single" has-permi="sysCompanyTemp" />
      <el-button v-hasPermi="['system:sysCompanyTemp:disable']" size="middle" :icon="disabledStatus === '1'?'el-icon-star-on':'el-icon-star-off'" :disabled="single" @click="handleStatusChange">
        {{ disabledContent }}
      </el-button>
      <el-button v-hasPermi="['system:sysCompanyTemp:fixation']" size="middle" :disabled="single" @click="fxiedBaseTemp">{{ isFixed === '0'? '取消固定基础套餐' : '固定基础套餐' }}</el-button>
    </div>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="tableData"
      stripe
      class="table-list"
      :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
        (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
      :row-style="rowClass"
      @selection-change="handleSelectionChange"
      @row-click="rowChecked"
    >
      <el-table-column type="selection" width="38" align="center" />
      <el-table-column label="套餐名称" prop="name" align="center" min-width="200" />
      <el-table-column label="套餐类型" prop="typeName" align="center" min-width="200" />
      <el-table-column label="套餐状态" prop="status" align="center" min-width="40">
        <template slot-scope="scope">
          <span v-if="scope.row.status=== '0'">正常</span>
          <span v-if="scope.row.status=== '1'">停用</span>
        </template>
      </el-table-column>
      <el-table-column label="是否为基础套餐" prop="status" align="center" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isFixed === '0'">基础套餐</span>
          <span v-if="scope.row.isFixed === '1'">非基础套餐</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者姓名" prop="createName" align="center" min-width="80" />
    </el-table>

    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <addDialog ref="addDialog" />
  </div>
</template>

<script>
import { listComTemp, updateComTempStatus, delComTemp, ComTempChangeStatus } from '@/api/enterprise/company-temp'
import { mapState } from 'vuex'
import addDialog from './components/addDialog'
// 按钮组件
import systemBtns from '@/components/Common/Btns/systemBtns'
import { listCompanyTempType } from '@/api/enterprise/company-temp-type'
export default {
  name: 'CompanyTemp',
  components: {
    systemBtns,
    addDialog
  },
  data() {
    return {
      // 高级设置显示隐藏
      highLevelSet: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的行对象
      multipleSelection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 启用/停用显示状态
      disabledStatus: '0',
      disabledContent: '停用',
      currentRow: {},
      // 总条数
      total: 0,
      // 表格数据
      tableData: [],
      selectRow: [],

      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: this.fristPageSize,
        name: '',
        type: '',
        status: '0'
      },
      // 查询参数中的日期
      dateRange: [],
      // 接收高级设置子组件返回的数据
      highLevelQueryParams: '',
      companyTypeOptions: [{ name: '全部', id: '' }],
      isFixed: '' // 是否为固定套餐
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  watch: {
    multipleSelection(data) {
      this.selectRow = []
      if (data.length > 0) {
        data.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(res => {
      this.statusOptions = res.data.rows
    })
    this.getCompanyType()
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      listComTemp(this.changeDateRange(this.queryParams, this.dateRange)).then(res => {
        if (res) {
          this.tableData = res.data.rows
          this.total = res.data.total
          this.loading = false
          // this.addTaleData()
        } else {
          this.msgError(res.message)
        }
      })
    },
    // 获取企业套餐类型信息
    getCompanyType() {
      listCompanyTempType({ status: '0' }).then(res => {
        if (res) {
          this.companyTypeOptions = { ...this.companyTypeOptions, ...res.data.rows }
        } else {
          this.msgError(res.message)
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (JSON.stringify(selection[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        selection = []
      }
      this.isFixed = '1'
      this.multipleSelection = selection
      if (this.multipleSelection.length === 1) {
        this.isFixed = this.multipleSelection[0].isFixed
        this.disabledStatus = this.multipleSelection[0].status
        if (this.disabledStatus === '0') {
          this.disabledContent = '停用'
        } else {
          this.disabledContent = '启用'
        }
      }
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      if (selection.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(selection.pop())
      }
    },
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // list表格填充空白行
    addTaleData() {
      if (this.tableData.length < this.fristPageSize) {
        const arr = {}
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1

      // 将高级设置所要查询的字段放到查询参数的对象中，key值自定义，与后台配合
      // 高级设置组件显示则查询，不显示则清空高级设置中添加的查询字段
      // if (this.highLevelSet === true) {
      //   if (this.highLevelQueryParams[0].model !== '') {
      //     this.dateRange = this.highLevelQueryParams[0].model
      //   }
      // } else {
      //   this.dateRange = []
      // }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      // 重置按钮对高级设置子组件中绑定的model值的操作
      this.queryParams.dateRange = []
      this.dateRange = []
      this.handleQuery()
    },
    // 套餐状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + row.name + '套餐吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.status === '0') {
            row.status = '1'
          } else {
            row.status = '0'
          }
          const formdata = {
            'id': row.id,
            'status': row.status
          }
          updateComTempStatus(formdata).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {
          this.msgInfo('已取消')
        })
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addDialog.handleAdd('新增企业套餐', this.companyTypeOptions)
    },

    /** 修改按钮操作 */
    handleUpdate() {
      this.$refs.addDialog.handleAdd('修改企业套餐', this.companyTypeOptions, this.ids)
    },
    // 固定基本套餐
    fxiedBaseTemp() {
      this.$confirm('您确定要将此套餐固定为基础套餐吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const isFixed = this.isFixed === '0' ? 1 : 0
        const data = {
          id: this.multipleSelection[0].id,
          isFixed: isFixed
        }
        await ComTempChangeStatus(data)
        this.getList()
        this.msgSuccess('修改成功')
      }).catch(() => {})
    },

    /** 删除按钮操作 */
    handleDelete() {
      let ids = ''
      const child = this.multipleSelection
      for (let i = 0; i < child.length; i++) {
        ids += child[i].id + ','
      }
      // 去掉最后一个逗号
      if (ids.length > 0) {
        ids = ids.substr(0, ids.length - 1)
      }
      this.$confirm(
        '是否确认删除数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delComTemp(ids)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function() {})
    }
  }
}
</script>
